<?php


namespace App\Repositories\Services;


use App\Lib\Tool\Tags;
use App\Repositories\Contracts\NodeRepository;
use App\Repositories\Eloquent\Admin\AdminRoleModel;
use App\Repositories\Eloquent\Admin\AdminRoleNodeModel;
use App\Repositories\Eloquent\Admin\SysNodeModel;
use EasySwoole\Component\Singleton;
use mysql_xdevapi\Session;

class Node implements NodeRepository
{
    use Singleton;
    protected $status;
    protected $nodeModel;
    protected $adminRoleModel;
    protected $adminRoleNodeModel;
    protected $admin;
    // 错误信息
    public $errors = array(
        1=>'success',
        111 => '404  not found ctr !',
        222 => 'Request method error ! ',
        333 => 'Sorry, you are not logged in',
    );

    function __construct()
    {
        $this->nodeModel = new SysNodeModel();
        $this->admin = new Admin();
        $this->adminRoleModel = new AdminRoleModel();
        $this->adminRoleNodeModel = new AdminRoleNodeModel();
    }

    //节点验证
    public function checkNode(string $url = '',$method = '')
    {
        $nodes = '';
        //节点
        $nodeObj = $this->nodeModel->getItemByUrl($url);
        if(empty($nodeObj)){
             return $this->returnError(111,$url);
        }
        //验证请求

        if($method !=strtoupper($nodeObj->method)){
            return $this->returnError(222);
        }
        //验证登录
        $adminItem = [];
        if($nodeObj->islogin == 1){
            list($status,$msg,$adminItem) = $this->admin->checkLogin();
            if($status == 0 ){
                return $this->returnError(333,$msg);
            }
            $idsDatas = $this->adminRoleNodeModel->getRoleNodes($adminItem['id']);
            $sys_left_nodes = $this->nodeModel->getAllForList($idsDatas);

            $html_left_node = Tags::html_left_nodes($sys_left_nodes);
            $nodes = $html_left_node;
        }
        return $this->returnError(1,'',$nodeObj->name,$nodes,$adminItem);

    }


    public function returnError(int $index = 0,string $msg = '',string $name = '',string $nodes = '',array $adminItem = []) {
        return [$index,$this->errors[$index].$msg,$name,$nodes,$adminItem];
    }

}